package com.yk.faceapplication.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.allinpay.xed.R;
import com.yk.faceapplication.MyApplication;
import com.yk.faceapplication.adapter.LoanPurposeAdapter;
import com.yk.faceapplication.adapter.LoanTermAdapter;
import com.yk.faceapplication.callback.LoanPurposeCallback;
import com.yk.faceapplication.callback.OptionCallback;
import com.yk.faceapplication.callback.TakePicCallback;
import com.yk.faceapplication.entity.Purpose;
import com.yk.faceapplication.entity.StudyInfo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ActivityUtil {

    public static boolean isAuth(Context ctx) {
        if (((MyApplication) ctx.getApplicationContext()).getMember().getSubs() == null || ((MyApplication) ctx.getApplicationContext()).getMember().getSubs().isEmpty()) {
            return false;
        }
        return true;
    }

    public static boolean isFace(Context ctx) {
        if (((MyApplication) ctx.getApplicationContext()).getMember().getPeople() == null || ((MyApplication) ctx.getApplicationContext()).getMember().getCards() == null || ((MyApplication) ctx.getApplicationContext()).getMember().getCards().isEmpty()) {
            return false;
        }
        return true;
    }

    public static int getScreenWidth(Activity act) {
        DisplayMetrics dm = new DisplayMetrics();
        act.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;// 宽度 像素
    }


    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int getScreenHeight(Activity act) {
        DisplayMetrics dm = new DisplayMetrics();
        act.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;// 高度 像素
    }


    public static float getScreenDensity(Activity act) {
        DisplayMetrics dm = new DisplayMetrics();
        act.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.density;
    }

    public static int dp2Px(Activity act, int dp) {
        return (int) (dp * getScreenDensity(act));
    }

    public static boolean hasSDCard() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    public static void changeKeyboard(Activity act) {
        // InputMethodManager imm = (InputMethodManager) act
        // .getSystemService(Context.INPUT_METHOD_SERVICE);
        // // 得到InputMethodManager的实例
        // if (imm.isActive()) {
        // // 如果开启
        // imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
        // InputMethodManager.HIDE_NOT_ALWAYS);
        // // 关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
        // }
        if (act.getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED) {
            act.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    public final static String FOLDER_CHAT_MSG_IMG = "/sdcard/occ/chat/msg/img";
    public final static String FOLDER_TEMP_FILE_IMG = "/sdcard/liveness/img/";
    public final static String FOLDER_USER_AVATAR = "/sdcard/occ/user/avatar/";


    public static void saveTempFileImg(Bitmap bmp, String fileName) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        LogDebugger.info("save img:" + baos.toByteArray().length);

        File file = new File(FOLDER_TEMP_FILE_IMG);
        if (!file.exists())
            file.mkdirs();
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(FOLDER_TEMP_FILE_IMG + fileName);
            if (fileName.endsWith("png")) {
                bmp.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            } else {
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            }
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void saveAvatarBitmapToPic(Bitmap bmp, String fileName) {
        File file = new File(FOLDER_CHAT_MSG_IMG);
        if (!file.exists())
            file.mkdirs();
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file.getPath() + "/" + fileName);
            if (fileName.endsWith("png")) {
                bmp.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            } else {
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            }
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Bitmap getBitmapFromSD(String fileName) {
        Bitmap bmpDefaultPic;
        bmpDefaultPic = BitmapFactory.decodeFile(FOLDER_CHAT_MSG_IMG + fileName, null);
        return bmpDefaultPic;
    }


    public static void startActivity(Activity act, Intent intent, int type) {
        act.startActivity(intent);
        switch (type) {
            case 1:

                break;
        }
    }

    public static void applyFont(final Context context, final View root, final String fontName) {
        try {
            if (root instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) root;
                for (int i = 0; i < viewGroup.getChildCount(); i++)
                    applyFont(context, viewGroup.getChildAt(i), fontName);
            } else if (root instanceof TextView)
                ((TextView) root).setTypeface(Typeface.createFromAsset(context.getAssets(), fontName));
        } catch (Exception e) {
            Log.e("", String.format("Error occured when trying to apply %s font for %s view", fontName, root));
            e.printStackTrace();
        }
    }

    public static void initWebView(WebView mWebview) {
        mWebview.getSettings().setRenderPriority(RenderPriority.HIGH);
        mWebview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // 设置
        // 缓存模式
        // 开启 DOM storage API 功能
        mWebview.getSettings().setDomStorageEnabled(true);
        // 开启 database storage API 功能
        mWebview.getSettings().setDatabaseEnabled(true);
        // String cacheDirPath =
        // getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME;
        // String cacheDirPath =
        // getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
        // 设置数据库缓存路径
        // mWebview.getSettings().setDatabasePath(cacheDirPath);
        // 设置 Application Caches 缓存目录
        // mWebview.getSettings().setAppCachePath(cacheDirPath);
        // 开启 Application Caches 功能
        mWebview.getSettings().setAppCacheEnabled(true);

        // 支持javascript
        mWebview.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        mWebview.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        mWebview.getSettings().setBuiltInZoomControls(true);
        // 扩大比例的缩放
        mWebview.getSettings().setUseWideViewPort(true);
        // 自适应屏幕
        mWebview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);

        mWebview.getSettings().setLoadWithOverviewMode(true);
    }

    public static void startActivity(Activity act, @SuppressWarnings("rawtypes") Class cls) {
        Intent intent = new Intent(act, cls);
        act.startActivity(intent);
    }

    public static Bitmap getRoundBitmap(Bitmap bmp) {
        // 获得图片的宽，并创建结果bitmap
        int width = bmp.getWidth();
        Bitmap resultBmp = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        Canvas canvas = new Canvas(resultBmp);
        // 画圆
        canvas.drawCircle(width / 2, width / 2, width / 2, paint);
        canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));// 选择交集去上层图片
        // paint.setAntiAlias(true);
        canvas.drawBitmap(bmp, 0, 0, paint);
        return resultBmp;
    }

    public static boolean isMobileNO(String mobiles) {
        if (mobiles == null || mobiles.length() != 11) {
            return false;
        }
        Pattern p = Pattern.compile("^((1[0-9]))\\d{9}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }


    public static boolean isNetworkAvailable(Context ctx) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
        return (info == null) ? false : info.isConnected() && info.isAvailable();
    }


    public static boolean editIsNull(EditText et) {
        if (et.getText().toString().trim().equals("")) {
            return true;
        }
        return false;
    }

    public static boolean textIsNull(TextView et) {
        if (et.getText().toString().trim().equals("")) {
            return true;
        }
        return false;
    }


    public static void removeSharedPreferences(SharedPreferences sharePreferences) {

    }

    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    Log.i("后台", appProcess.processName);
                    return true;
                } else {
                    Log.i("前台", appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }


    public static boolean isNetworkAvailable2(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            //			ToastUtils.show(context, "当前网络不可用,请检查网络后重试.");
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        //		ToastUtils.show(context, "当前网络不可用,请检查网络后重试.");
        return false;
    }

    public static Dialog createLoadingDialog(Context context, String msg) {

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.loading_dialog, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);// 加载布局
        // main.xml中的ImageView
        ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
        // 加载动画
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(context, R.anim.load_animation);
        // 使用ImageView显示动画
        spaceshipImage.startAnimation(hyperspaceJumpAnimation);
        tipTextView.setText(msg);// 设置加载信息

        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog

        loadingDialog.setCancelable(false);// 不可以用“返回键”取消
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));// 设置布局
        return loadingDialog;

    }

    public static Dialog createLoanTermDialog(Activity context, final List<StudyInfo> data, final OptionCallback callback) {

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.bottom_dialog, null);// 得到加载view
        RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.dialog_view);// 加载布局
        TextView tipTextView = (TextView) v.findViewById(R.id.cancel_tv);// 取消
        ListView listView = (ListView) v.findViewById(R.id.option_listview);
        tipTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callback.cancel();
            }
        });
        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog
        int height = getScreenHeight(context);
        int width = getScreenWidth(context);
        loadingDialog.setCancelable(false);// 不可以用“返回键”取消
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(width, height - 50));// 设置布局
        listView.setAdapter(new LoanTermAdapter(context, data));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                callback.success(data.get(position));
            }
        });
        return loadingDialog;

    }

    public static Dialog createLoanPurposeDialog(final Activity context, final List<Purpose> data, final LoanPurposeCallback callback) {

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.loan_purpose_dialog, null);// 得到加载view
        RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.dialog_view);// 加载布局
        TextView tipTextView = (TextView) v.findViewById(R.id.cancel_tv);// 取消
        tipTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callback.cancel();
            }
        });
        final ListView listView = (ListView) v.findViewById(R.id.option_listview);
        ListView typeListView = (ListView) v.findViewById(R.id.type_listview);
        typeListView.setAdapter(new LoanPurposeAdapter(context, data, null));
        typeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<Purpose> list = data.get(position).getChildren();
                if (list.size() == 0) {
                    callback.success(data.get(position));
                    listView.setAdapter(null);
                } else {
                    listView.setAdapter(new LoanPurposeAdapter(context, list, callback));
                }
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog
        int height = getScreenHeight(context);
        int width = getScreenWidth(context);
        loadingDialog.setCancelable(false);// 不可以用“返回键”取消
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(width, height - 50));// 设置布局
        //		listView.setAdapter(new LoanTermAdapter(context, data));
        //		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        //			@Override
        //			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //				callback.success(data.get(position));
        //			}
        //		});
        return loadingDialog;

    }

    public static boolean isPassworkFormat(String pwd) {
        boolean isDigit = false;//定义一个boolean值，用来表示是否包含数字
        boolean isLetter = false;//定义一个boolean值，用来表示是否包含字母
        for (int i = 0; i < pwd.length(); i++) {
            if (Character.isDigit(pwd.charAt(i))) {   //用char包装类中的判断数字的方法判断每一个字符
                isDigit = true;
            }
            if (Character.isLetter(pwd.charAt(i))) {  //用char包装类中的判断字母的方法判断每一个字符
                isLetter = true;
            }
        }
        //    String regex = "^[a-zA-Z0-9]+$";
        //    boolean isRight = isDigit && isLetter && pwd.matches(regex);
        String regex = "^[a-zA-Z0-9]+$";
        boolean isRight = isDigit && isLetter;
        return isRight;

    }

    public static Dialog createTakePicDialog(Activity context, final TakePicCallback callback) {

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.take_pic_dialog, null);// 得到加载view
        RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.dialog_view);// 加载布局
        TextView tipTextView = (TextView) v.findViewById(R.id.cancel_tv);// 取消
        tipTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callback.cancel();
            }
        });
        TextView takePhotoTV = (TextView) v.findViewById(R.id.take_photo_tv);// 取消
        TextView takePicTV = (TextView) v.findViewById(R.id.take_pic_tv);// 取消
        takePicTV.setVisibility(View.GONE);
        takePhotoTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callback.takePhoto();
            }
        });
        takePicTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callback.takeImg();
            }
        });

        Dialog loadilog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog
        int height = getScreenHeight(context);
        int width = getScreenWidth(context);
        loadilog.setCancelable(false);// 不可以用“返回键”取消
        loadilog.setContentView(layout, new LinearLayout.LayoutParams(width, height - 50));// 设置布局

        return loadilog;

    }


    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;

        while (baos.toByteArray().length / 1024 > 200) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    public static Bitmap compressImage(Bitmap image, File file) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;

        while (baos.toByteArray().length / 1024 > 200) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    private static BitmapFactory.Options getBitmapOption(int inSampleSize) {
        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
    }

    public static Bitmap compressImage(String filePath) {
        Bitmap image = BitmapFactory.decodeFile(filePath, getBitmapOption(2));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        LogDebugger.info(baos.toByteArray().length + "");
        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于200kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        LogDebugger.info(baos.toByteArray().length + "");
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    public static void compressImageToFile(String filePath, String fileName) {
        Bitmap bmp = BitmapFactory.decodeFile(filePath, getBitmapOption(2));
        // 0-100 100为不压缩
        int options = 90;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        LogDebugger.info("图片大小:"+baos.toByteArray().length);
        while (baos.toByteArray().length / 1024 > 200) { // 循环判断如果压缩后图片是否大于200kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
            LogDebugger.info("图片大小:"+baos.toByteArray().length);
        }

        File file = new File(FOLDER_TEMP_FILE_IMG);
        if (!file.exists())
            file.mkdirs();
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file.getPath() + "/" + fileName);
            fileOutputStream.write(baos.toByteArray());
            fileOutputStream.flush();
            fileOutputStream.close();
            if (bmp != null && !bmp.isRecycled()) {
                bmp.recycle();
                bmp = null;
            }
            baos.reset();
            baos = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void compressImageToFile(Bitmap bmp, String fileName) {
        // 0-100 100为不压缩
        int options = 90;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        LogDebugger.info("图片大小:"+baos.toByteArray().length);
        while (baos.toByteArray().length / 1024 > 200) { // 循环判断如果压缩后图片是否大于200kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
            LogDebugger.info("图片大小:"+baos.toByteArray().length);
        }

        File file = new File(FOLDER_TEMP_FILE_IMG);
        if (!file.exists())
            file.mkdirs();
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file.getPath() + "/" + fileName);
            fileOutputStream.write(baos.toByteArray());
            fileOutputStream.flush();
            fileOutputStream.close();
            if (bmp != null && !bmp.isRecycled()) {
                bmp.recycle();
                bmp = null;
            }
            baos.reset();
            baos = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
